#include "CGrid.h"

#ifndef IOSTREAM_HEADER
	#include <iostream>
	#define IOSTREAM_HEADER
#endif

#ifndef FSTREAM_HEADER
    #include <fstream>
    #define FSTREAM_HEADER
#endif

CGrid::CGrid(char* Filename, unsigned int Width, unsigned int Height)
{
    _Width = Width;
    _Height = Height;

    importGrid(Filename);
}

CGrid::~CGrid()
{
    for(unsigned int i = 0; i < Nodes.size(); i++)
        delete Nodes[i];
}

CNode::CNode*  CGrid::GetNode(unsigned int X, unsigned int Y)
{
    if(X + Y * _HNodeCount < Nodes.size())
        return Nodes[X + Y * _HNodeCount];

    return NULL;
}

std::vector<CNode::CNode*> CGrid::GetAdjacentNodes(unsigned int X, unsigned int Y)
{
    std::vector<CNode::CNode*> tmpNodes;

    //if(X > 0 && Y > 0) tmpNodes.push_back(GetNode(X - 1, Y - 1));
    if(Y > 0) tmpNodes.push_back(GetNode(X, Y - 1));
    //if(X < _HNodeCount - 1 && Y > 0) tmpNodes.push_back(GetNode(X + 1, Y - 1));

    if(X > 0) tmpNodes.push_back(GetNode(X - 1, Y));
    if(X < _HNodeCount - 1) tmpNodes.push_back(GetNode(X + 1, Y));

    //if(X > 0 && Y < _VNodeCount - 1) tmpNodes.push_back(GetNode(X - 1, Y + 1));
    if(Y < _VNodeCount - 1) tmpNodes.push_back(GetNode(X, Y + 1));
    //if(X < _HNodeCount - 1 && Y < _VNodeCount - 1) tmpNodes.push_back(GetNode(X + 1, Y + 1));

	return tmpNodes;
}

void CGrid::DrawAllNodes(SDL_Surface* Screen)
{
	for(unsigned int i = 0; i < Nodes.size(); i++)
		Nodes[i]->Draw(Screen);
}

std::vector<std::string> CGrid::getFile(char* Filename)
{
    std::ifstream inputStream;
    std::vector<std::string> fileLines;
    std::string tmpLine;

    inputStream.open(Filename);

    if(inputStream)
    {
        while(!inputStream.eof())
        {
            getline(inputStream, tmpLine);
            std::cout << tmpLine << std::endl;

            fileLines.push_back(tmpLine);
        }

        return fileLines;
    }

    return (std::vector<std::string>)NULL;
}

void CGrid::importGrid(char* Filename)
{
    std::vector<std::string> labData = getFile(Filename);

    _HNodeCount = labData[0].length();
    _VNodeCount = labData.size() - 1;

    nodeWidth = _Width / _HNodeCount;
    nodeHeight = _Height / _VNodeCount;

    for(unsigned int Y = 0; Y < _VNodeCount; Y++)
        for(unsigned int X = 0; X < _HNodeCount; X++)
            addNode(X, Y, labData[Y].substr(X, 1).c_str()[0]);
}

void CGrid::addNode(unsigned int X, unsigned int Y, char Type)
{
    NodeType tmpType;
    switch(Type)
    {
        case 'D':
            tmpType = START;

            break;

        case 'A':
            tmpType = END;
            break;

        case 'x':
            tmpType = WALL;
            break;

        case '*':
            tmpType = GROUND;
            break;
    }

    CNode::CNode* tmpNode = new CNode::CNode(X, Y, nodeWidth, nodeHeight, tmpType);

    if(tmpType == START) StartNode = tmpNode;
    if(tmpType == END) EndNode = tmpNode;

    Nodes.push_back(tmpNode);
}
